package com.example.zzx.dovebook.personalcenter.follow.follower

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.example.baselibrary.LoadCallback
import com.example.baselibrary.net.HttpUtil
import com.example.zzx.dovebook.base.BaseLiveData
import com.example.zzx.dovebook.base.BaseViewModel
import com.example.zzx.dovebook.base.ValueWrapper
import com.example.zzx.dovebook.base.ValueWrapper.*
import com.example.zzx.dovebook.personalcenter.follow.UserFollow

class FollowerViewModel(repository: FollowerRepository): BaseViewModel<FollowerRepository>(repository) {

    private val queryFollowersKeys = arrayOf("userId", "createAt")

    private val followKeys = arrayOf("fromUserId", "toUserId")

    private val cancelFollowKeys = arrayOf("fromUserId", "toUserId")

    fun queryFollowers(userId: String, lastItemCreateAt: Long): LiveData<ValueWrapper<*>> {
        val result = BaseLiveData<List<UserFollow>>()
        val paraMap = HttpUtil.wrapParams(queryFollowersKeys, userId, lastItemCreateAt)
        repository.queryFollowers(paraMap, object: LoadCallback<List<UserFollow>> {
            override fun loadSuccess(data: List<UserFollow>?) {
                result.postValue(data, TYPE_NORMAL)
            }

            override fun loadFailed(errorMessage: String?) {
                postErrorMessage(errorMessage)
                result.postValue(null, TYPE_FAILED)
            }

            override fun loadNull(message: String?) {
                result.postValue(null, TYPE_NO_CONTENT)
            }

        })
        return result
    }

    fun follow(fromUserId: String, toUserId: String): LiveData<Int> {
        val result = MutableLiveData<Int>()
        val paraMap = HttpUtil.wrapParams(followKeys, fromUserId, toUserId)
        repository.follow(paraMap, object: LoadCallback<Int> {
            override fun loadSuccess(data: Int?) {
                result.postValue(data)
            }

            override fun loadFailed(errorMessage: String?) {
                postErrorMessage(errorMessage)
            }

            override fun loadNull(message: String?) {
            }

        })
        return result
    }

    fun cancelFollow(fromUserId: String, toUserId: String): LiveData<Int> {
        val result = MutableLiveData<Int>()
        val paraMap = HttpUtil.wrapParams(cancelFollowKeys, fromUserId, toUserId)
        repository.cancelFollow(paraMap, object: LoadCallback<Int> {
            override fun loadSuccess(data: Int?) {
                result.postValue(data)
            }

            override fun loadFailed(errorMessage: String?) {
                postErrorMessage(errorMessage)
            }

            override fun loadNull(message: String?) {
            }

        })
        return result
    }
}